import { useId } from 'react';
import { DndProvider } from 'react-dnd';
import { HTML5Backend } from 'react-dnd-html5-backend';
import { DndCard } from '../DndCard';
import { SourceInterface } from '../SourceSelect/Entity/interface';
import { CourseListItem } from './CourseListItem';
import { CoursewaresListEmpty } from './CoursewarseListEmpty';

interface CoursewaresListPorps {
  value?: SourceInterface[];
  onChange?(value: SourceInterface[]): void;
  resourceType?: string;
}

const style: React.CSSProperties = {
  display: 'flex',
  flexDirection: 'column',
  gap: 16,
};

/**
 * 可以操作
 */
export function CoursewaresList({ value, onChange, resourceType }: CoursewaresListPorps) {
  const id = useId();
  return (
    <CoursewaresListEmpty empty={(value?.length ?? 0) === 0}>
      <DndProvider backend={HTML5Backend}>
        <ul style={style}>
          {value?.map((course, index) => {
            return (
              <DndCard
                key={course.id}
                index={index}
                moveCard={(a, b) => {
                  const nextValue = value.slice();
                  const temp = nextValue[a];
                  nextValue[a] = nextValue[b];
                  nextValue[b] = temp;
                  onChange?.(nextValue);
                }}
                dragAndDropKey={id}
              >
                <li>
                  <CourseListItem
                    name={course.name}
                    guid={course.id}
                    type={course.type}
                    canDel={course.parentType == '课件包' ? false : true}
                    resourceType={resourceType}
                    onDelete={() => {
                      const next = value.slice();
                      next.splice(index, 1);
                      onChange?.(next);
                    }}
                  />
                </li>
              </DndCard>
            );
          })}
        </ul>
      </DndProvider>
    </CoursewaresListEmpty>
  );
}

/**
 * @desc 仅用于观看的课件列表
 */
export function CoursewaresListView({ value, resourceType }: CoursewaresListPorps) {
  return (
    <CoursewaresListEmpty empty={(value?.length ?? 0) === 0}>
      <ul style={style}>
        {value?.map((course) => {
          return (
            <li key={course.id}>
              <CourseListItem
                name={course.name}
                guid={course.id}
                type={course.type}
                resourceType={resourceType}
                isCharge={course.isCharge || 0}
              ></CourseListItem>
            </li>
          );
        })}
      </ul>
    </CoursewaresListEmpty>
  );
}
